package org.liaohailong.library.db

import android.database.Cursor
import android.text.TextUtils
import org.liaohailong.library.db.annotation.Column

/**
 * Author: liaohailong
 * Date: 2019/4/4
 * Time: 6:10 PM
 * Description: sql数据转型实例类
 **/
class SQLItemParser<T>(private val clazz: Class<T>) {

    fun parse(cursor: Cursor): T {
        val newInstance = clazz.newInstance()
        for (declaredField in clazz.declaredFields) {
            for (declaredAnnotation in declaredField.declaredAnnotations) {
                if (declaredAnnotation is Column) {
                    val name = if (TextUtils.isEmpty(declaredAnnotation.name)) declaredField.name else declaredAnnotation.name
                    val columnIndex = cursor.getColumnIndex(name)
                    if (columnIndex != -1) {
                        val value: Any = when (declaredField.type) {
                            String::class.java -> cursor.getString(columnIndex)
                            Int::class.java -> cursor.getInt(columnIndex)
                            Long::class.java -> cursor.getLong(columnIndex)
                            Float::class.java -> cursor.getFloat(columnIndex)
                            Double::class.java -> cursor.getDouble(columnIndex)
                            else -> cursor.getString(columnIndex)
                        }
                        declaredField.isAccessible = true
                        declaredField.set(newInstance, value)
                    }
                    break
                }
            }
        }
        return newInstance
    }
}